package com.gsbelarus.gedemin.salary.fragment;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.text.Html;
import android.webkit.WebView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.gsbelarus.gedemin.lib.sync.protocol.SyncServiceModel;
import com.gsbelarus.gedemin.lib.sync.protocol.entity.SyncServiceTask;
import com.gsbelarus.gedemin.salary.App;
import com.gsbelarus.gedemin.salary.R;
import com.gsbelarus.gedemin.salary.activity.Main;
import com.gsbelarus.gedemin.salary.activity.PersonInfo;
import com.gsbelarus.gedemin.salary.entity.SyncRequestType;
import com.gsbelarus.gedemin.salary.service.SyncService;
import com.gsbelarus.gedemin.salary.util.CurrencyHelper;

public class SettingsFragment extends PrefFragment {

    public static final String PLAY_STORE_ANALYTISC_CAMPAIGN_PARAMETERS = "&referrer=utm_source%3Dapplication%26utm_medium%3DGedeminPayslip%2520app%26utm_content%3Drate%2520app%26utm_campaign%3DGedeminPayslip%2520app";
    public static final String GS_CONTACT_URL = "http://gsbelarus.com/pw/contact-us/";
    public static final String GS_CONTACT_ANALYTISC_CAMPAIGN_PARAMETERS = "?utm_source=application&utm_medium=GedeminPayslip%20app&utm_content=learn%20more&utm_campaign=GedeminPayslip%20app";

    public static final String WORK_MODE = "working_mode";

    public static final String LANG_PREF = "lang_listPref";
    public static final String CURRENCY_PREF = "currency_listPref";
    public static final String ADDRESS_SERVER = "address_server_editText";
    public static final String SYNC_PREF_BUTTON = "sync_pref_button";
    public static final String SYNC_BUTTON = "sync_button";

    public static final String ABOUT = "about";
    public static final String CHANGELOG = "changelog";
    public static final String RATE_APP = "rate_app";

    public static final int DEFAULT_LANG_PREF_ITEM = 0;

    private static final String VERSION_UNAVAILABLE = "N/A";

    private CurrencyHelper currencyHelper;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        currencyHelper = CurrencyHelper.getInstance(context);

        addPreferencesFromResource(R.xml.pref_settings);

        initListSummary(findPreference(LANG_PREF),
                getResources().getStringArray(R.array.language_list_title),
                DEFAULT_LANG_PREF_ITEM)
                .setOnPreferenceClickListener(getClickListener());

        initListSummary(findPreference(CURRENCY_PREF),
                getResources().getStringArray(R.array.currency_list),
                currencyHelper.getLastChoice().ordinal())
                .setOnPreferenceClickListener(getClickListener());

        initEditSummary(findPreference(ADDRESS_SERVER),
                getResources().getString(R.string.not_specified_text))
                .setOnPreferenceClickListener(getClickListener());

        findPreference(SYNC_PREF_BUTTON).setOnPreferenceClickListener(getClickListener());
        findPreference(SYNC_BUTTON).setOnPreferenceClickListener(getClickListener());

        findPreference(ABOUT).setOnPreferenceClickListener(getClickListener());
        findPreference(CHANGELOG).setOnPreferenceClickListener(getClickListener());
        findPreference(RATE_APP).setOnPreferenceClickListener(getClickListener());

        /** Проверяем запущена ли синхронизации, если запущена срабатывает BroadcastReceiver
         и выключает кнопки раздела Аутентификация */
        getActivity().startService(SyncServiceModel.getIntentWithTask(
                new Intent(context, SyncService.class), SyncServiceTask.TypeOfTask.NO_SYNC));
    }

    private Preference.OnPreferenceClickListener getClickListener() {
        return new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(final Preference preference) {
                if (findPreference(LANG_PREF) == preference) {
                    showListDialog(preference,
                            preference.getTitle().toString(),
                            getString(R.string.cancel_text),
                            getResources().getStringArray(R.array.language_list_title),
                            DEFAULT_LANG_PREF_ITEM,
                            new OnItemListChanged() {
                                @Override
                                public void onItemListChanged(String value, int position) {
                                    ((App) getActivity().getApplication()).changeLocale();
                                    Intent restartIntent = new Intent(context, Main.class);
                                    restartIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                    restartIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    startActivity(restartIntent);
//                                    System.exit(0);
                                }
                            });

                } else if (findPreference(CURRENCY_PREF) == preference) {
                    currencyHelper.showChoiceDialog(getActivity(), new CurrencyHelper.OnCurrencySwitcherChanged() {
                        @Override
                        public void onChanged(CurrencyHelper.Kind kind) {
                            preference.setSummary(getResources().getStringArray(R.array.currency_list)
                                    [currencyHelper.getLastChoice().ordinal()]);
                        }
                    });

                } else if (findPreference(ADDRESS_SERVER) == preference) {
                    showEditDialog(preference,
                            preference.getTitle().toString(),
                            getString(R.string.dialog_ok),
                            getString(R.string.cancel_text),
                            null,
                            new OnPositiveListener() {
                                @Override
                                public void onPositive() {
                                    putBoolean(WORK_MODE, isData(context));
                                }
                            });

                } else if (findPreference(SYNC_PREF_BUTTON) == preference) {
                    startActivity(new Intent(context, PersonInfo.class));

                } else if (findPreference(SYNC_BUTTON) == preference) {
                    getActivity().startService(SyncServiceModel.getIntentWithTask(new Intent(getActivity(), SyncService.class),
                            SyncServiceTask.TypeOfTask.SINGLE_SYNC,
                            new SyncRequestType(SyncRequestType.TypeOfRequest.DATA_MSG_REQUEST)));

                } else if (findPreference(ABOUT) == preference) {
                    String appVer;
                    try {
                        PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
                        appVer = packageInfo.versionName;
                    } catch (PackageManager.NameNotFoundException e) {
                        appVer = VERSION_UNAVAILABLE;
                    }

                    showAlertDialog(
                            Html.fromHtml(getString(R.string.app_name_and_version, appVer)),
                            getString(R.string.about_body),
                            getString(R.string.dialog_ok), null, getString(R.string.neutral_text),
                            new MaterialDialog.ButtonCallback() {
                                @Override
                                public void onNeutral(MaterialDialog dialog) {
                                    super.onNeutral(dialog);
                                    Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(GS_CONTACT_URL + GS_CONTACT_ANALYTISC_CAMPAIGN_PARAMETERS));
                                    startActivity(browserIntent);
                                }
                            });

                } else if (findPreference(CHANGELOG) == preference) {
                    MaterialDialog dialog = new MaterialDialog.Builder(getActivity())
                            .title(getResources().getString(R.string.pref_info_changelog))
                            .customView(R.layout.dialog_webview, false)
                            .positiveText(android.R.string.ok)
                            .build();
                    if (dialog.getCustomView() != null) {
                        WebView webView = (WebView) dialog.getCustomView().findViewById(R.id.webview);
                        if (webView != null) {
                            webView.getSettings().setDefaultTextEncodingName("utf-8");

                            StringBuilder content = new StringBuilder();                            ///TODO
                            String[] versions = getResources().getStringArray(R.array.changelog_versions);
                            String[] dates = getResources().getStringArray(R.array.changelog_dates);
                            String[] names = getResources().getStringArray(R.array.changelog_names);
                            content.append("<!DOCTYPE html><html><body>");
                            for (int i = 0; i < versions.length; i++) {
                                content.append("<p>&nbsp;&nbsp;&nbsp;&nbsp;<b>v")
                                        .append(versions[i])
                                        .append("</b> <font color=\"#888888\"> - ")
                                        .append(dates[i])
                                        .append("</font></p>\n<p>&nbsp;&nbsp;&nbsp;&nbsp;")
                                        .append(names[i])
                                        .append("</p>");
                            }
                            content.append("</body></html>");

                            webView.loadDataWithBaseURL(null, content.toString(),
                                    "text/html", "utf-8",null);
                        }
                    }
                    dialog.show();

                } else if (findPreference(RATE_APP) == preference) {
                    try {
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + context.getPackageName() +
                                PLAY_STORE_ANALYTISC_CAMPAIGN_PARAMETERS)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                    } catch (ActivityNotFoundException e) {
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" +
                                context.getPackageName() + PLAY_STORE_ANALYTISC_CAMPAIGN_PARAMETERS)));
                    }
                }
                return false;
            }
        };
    }

    public void setEnabledAuthPref(boolean flag) {
        findPreference(ADDRESS_SERVER).setEnabled(flag);
        findPreference(SYNC_PREF_BUTTON).setEnabled(flag);
        findPreference(SYNC_BUTTON).setEnabled(flag);
    }

    public static boolean isData(Context context) {
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
        return !pref.getString(SettingsFragment.ADDRESS_SERVER, "").isEmpty() &&
                !pref.getString(PersonInfoPrefFragment.SURNAME, "").isEmpty() &&
                !pref.getString(PersonInfoPrefFragment.FIRSTNAME, "").isEmpty() &&
                !pref.getString(PersonInfoPrefFragment.LIST_NUMBER, "").isEmpty() &&
                !pref.getString(PersonInfoPrefFragment.MIDDLENAME, "").isEmpty() &&
                !pref.getString(PersonInfoPrefFragment.PERSON_NUMBER, "").isEmpty();
    }
}
